import React from "react";
import {Tabs, Space, Input, DatePicker, Form, Button} from "antd";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import "@/views/commodity/style/style.less";
import {apiGetReturnOrderDetails, apiOrderRefundRefuse} from '@/request/doctor'
import {getDateTime3} from '@/utils/getDate'
import TheDialog from '@/components/TheDialog'

const {RangePicker} = DatePicker;
const {Search} = Input;
const {TabPane} = Tabs;
const {TextArea} = Input;

class Chargeback extends React.Component {
    roleIds = sessionStorage.getItem('roleName')
    state = {
        salesReturnStatus: '',
        columns1: [
            {
                title: "退单编号",
                dataIndex: "hospitalSalesReturnCode",
                key: "hospitalSalesReturnCode",
            },
            {
                title: "订单编号",
                dataIndex: "hospitalOrderCode",
                key: "hospitalOrderCode",
            },
            {
                title: "用户昵称",
                dataIndex: "nickName",
                key: "nickName",
            },
            {
                title: "订单金额（元）",
                dataIndex: "orderPrice",
                key: "orderPrice",
                render: (text, render) => {
                    return <React.$Price price={render.orderPrice}/>
                }
            },
            {
                title: "实付金额（元）",
                dataIndex: "payPrice",
                key: "payPrice",
                render: (text, render) => {
                    return <React.$Price price={render.payPrice}/>
                }
            },
            {
                title: "退款金额",
                dataIndex: "refundPrice",
                key: "refundPrice",
                render: (text, render) => {
                    return <React.$Price price={render.refundPrice}/>
                }
            },
            {
                title: "退单时间",
                dataIndex: "createTime",
                key: "createTime",
            },
            {
                title: "退单状态",
                dataIndex: "salesReturnStatus",
                key: "salesReturnStatus",
                render: (text, record) => {
                    let label = ''
                    switch (record.salesReturnStatus) {
                        case "1":
                            label = "退款中"
                            break
                        case "4":
                            label = "退款失败"
                            break
                        case "9":
                            label = "退款成功"
                            break
                        default:
                            label = "未知退款状态"
                    }
                    return label;
                }
            },
            {
                title: "退单原因",
                dataIndex: "refundCause",
                key: "refundCause",
            },
            {
                title: "操作",
                fixed: "right",
                render: (text, render) => {
                    return (
                        <div>
                            <TheButton hasPermi={['doctor:chargeback:view']}
                                onClick={() => this.props.history.push(`/doctor/chargeback/details/${render.hospitalSalesReturnId}`)}
                            >
                                查看订单
                            </TheButton>
                            {
                                this.roleIds.includes('库管') ? null : <span>
                  <TheButton hasPermi={['doctor:chargeback:agree']} onClick={() => this.chargebackConfirm(render.hospitalSalesReturnId)}>同意退款</TheButton>
                  <TheButton hasPermi={['doctor:chargeback:refuse']} onClick={() => this.chargebackRefused(render.hospitalSalesReturnId)}>拒绝退款</TheButton>
                </span>
                            }
                        </div>
                    );
                },
            },
        ],
        columns: [
            {
                title: "退单编号",
                dataIndex: "hospitalSalesReturnCode",
                key: "hospitalSalesReturnCode",
            },
            {
                title: "订单编号",
                dataIndex: "hospitalOrderCode",
                key: "hospitalOrderCode",
            },
            {
                title: "用户昵称",
                dataIndex: "nickName",
                key: "nickName",
            },
            {
                title: "订单金额（元）",
                dataIndex: "orderPrice",
                key: "orderPrice",
                render: (text, render) => {
                    return <React.$Price price={render.orderPrice}/>
                }
            },
            {
                title: "实付金额（元）",
                dataIndex: "payPrice",
                key: "payPrice",
                render: (text, render) => {
                    return <React.$Price price={render.payPrice}/>
                }
            },
            {
                title: "退款金额",
                dataIndex: "refundPrice",
                key: "refundPrice",
                render: (text, render) => {
                    return <React.$Price price={render.refundPrice}/>
                }
            },
            {
                title: "退单时间",
                dataIndex: "createTime",
                key: "createTime",
            },
            {
                title: "退单状态",
                dataIndex: "salesReturnStatus",
                key: "salesReturnStatus",
                render: (text, record) => {
                    let label = ''
                    switch (record.salesReturnStatus) {
                        case "1":
                            label = "退款中"
                            break
                        case "4":
                            label = "退款失败"
                            break
                        case "9":
                            label = "退款成功"
                            break
                        default:
                            label = "未知退款状态"
                    }
                    return label;
                }
            },
            {
                title: "退单原因",
                dataIndex: "refundCause",
                key: "refundCause",
            },
            {
                title: "操作",
                fixed: "right",
                render: (text, render) => {
                    if (render.salesReturnStatus == 1) {
                        return (
                            <div>
                                <TheButton hasPermi={['doctor:chargeback:view']}
                                    onClick={() => this.props.history.push(`/doctor/chargeback/details/${render.hospitalSalesReturnId}`)}
                                >
                                    查看订单
                                </TheButton>
                                {
                                    this.roleIds.includes('库管') ? null : <span>
                    <TheButton hasPermi={['doctor:chargeback:agree']} onClick={() => this.chargebackConfirm(render.hospitalSalesReturnId)}>同意退款</TheButton>
                    <TheButton hasPermi={['doctor:chargeback:refuse']} onClick={() => this.chargebackRefused(render.hospitalSalesReturnId)}>拒绝退款</TheButton>
                  </span>
                                }
                            </div>
                        );
                    } else {
                        return (
                            <div>
                                <TheButton hasPermi={['doctor:chargeback:view']}
                                    onClick={() => this.props.history.push(`/doctor/chargeback/details/${render.hospitalSalesReturnId}`)}
                                >
                                    查看订单
                                </TheButton>
                            </div>
                        )
                    }

                },
            },
        ],
        columns4: [
            {
                title: "退单编号",
                dataIndex: "hospitalSalesReturnCode",
                key: "hospitalSalesReturnCode",
            },
            {
                title: "订单编号",
                dataIndex: "hospitalOrderCode",
                key: "hospitalOrderCode",
            },
            {
                title: "用户昵称",
                dataIndex: "nickName",
                key: "nickName",
            },
            {
                title: "订单金额（元）",
                dataIndex: "orderPrice",
                key: "orderPrice",
                render: (text, render) => {
                    return <React.$Price price={render.orderPrice}/>
                }
            },
            {
                title: "实付金额（元）",
                dataIndex: "payPrice",
                key: "payPrice",
                render: (text, render) => {
                    return <React.$Price price={render.payPrice}/>
                }
            },
            {
                title: "退款金额",
                dataIndex: "refundPrice",
                key: "refundPrice",
                render: (text, render) => {
                    return <React.$Price price={render.refundPrice}/>
                }
            },
            {
                title: "退单时间",
                dataIndex: "createTime",
                key: "createTime",
            },
            {
                title: "退单状态",
                dataIndex: "salesReturnStatus",
                key: "salesReturnStatus",
                render: (text, record) => {
                    let label = ''
                    switch (record.salesReturnStatus) {
                        case "1":
                            label = "退款中"
                            break
                        case "4":
                            label = "退款失败"
                            break
                        case "9":
                            label = "退款成功"
                            break
                        default:
                            label = "未知退款状态"
                    }
                    return label;
                }
            },
            {
                title: "退单原因",
                dataIndex: "refundCause",
                key: "refundCause",
            },
            {
                title: "操作",
                fixed: "right",
                render: (text, render) => {
                    return (
                        <div>
                            <TheButton hasPermi={['doctor:chargeback:view']}
                                onClick={() => this.props.history.push(`/doctor/chargeback/details/${render.hospitalSalesReturnId}`)}
                            >
                                查看订单
                            </TheButton>
                        </div>
                    );
                },
            },
        ],
        columns9: [
            {
                title: "退单编号",
                dataIndex: "hospitalSalesReturnCode",
                key: "hospitalSalesReturnCode",
            },
            {
                title: "订单编号",
                dataIndex: "hospitalOrderCode",
                key: "hospitalOrderCode",
            },
            {
                title: "用户昵称",
                dataIndex: "nickName",
                key: "nickName",
            },
            {
                title: "订单金额（元）",
                dataIndex: "orderPrice",
                key: "orderPrice",
                render: (text, render) => {
                    return <React.$Price price={render.orderPrice}/>
                }
            },
            {
                title: "实付金额（元）",
                dataIndex: "payPrice",
                key: "payPrice",
                render: (text, render) => {
                    return <React.$Price price={render.payPrice}/>
                }
            },
            {
                title: "退款金额",
                dataIndex: "refundPrice",
                key: "refundPrice",
                render: (text, render) => {
                    return <React.$Price price={render.refundPrice}/>
                }
            },
            {
                title: "退单时间",
                dataIndex: "createTime",
                key: "createTime",
            },
            {
                title: "退单状态",
                dataIndex: "salesReturnStatus",
                key: "salesReturnStatus",
                render: (text, record) => {
                    let label = ''
                    switch (record.salesReturnStatus) {
                        case "1":
                            label = "退款中"
                            break
                        case "4":
                            label = "退款失败"
                            break
                        case "9":
                            label = "退款成功"
                            break
                        default:
                            label = "未知退款状态"
                    }
                    return label;
                }
            },
            {
                title: "退单原因",
                dataIndex: "refundCause",
                key: "refundCause",
            },
            {
                title: "操作",
                fixed: "right",
                render: (text, render) => {
                    return (
                        <div>
                            <TheButton hasPermi={['doctor:chargeback:view']}
                                onClick={() => this.props.history.push(`/doctor/chargeback/details/${render.hospitalSalesReturnId}`)}
                            >
                                查看订单
                            </TheButton>
                        </div>
                    );
                },
            },
        ],
        dataSource: [],
        dataSource1: [],
        dataSource4: [],
        dataSource9: [],
        pageData: {
            pageNo: 1,
            pageSize: 10,
        },
        pageData1: {
            pageNo: 1,
            pageSize: 10,
        },
        pageData4: {
            pageNo: 1,
            pageSize: 10,
        },
        pageData9: {
            pageNo: 1,
            pageSize: 10,
        },
        total1: 0,
        total4: 0,
        total9: 0,
        tabData: [
            {
                label: '全部',
                value: ''
            },
            {
                label: '退款中',
                value: '1'
            },
            {
                label: '退款成功',
                value: '9'
            },
            {
                label: '退款失败',
                value: '4'
            },
        ],
        searchValue: {
            nickName: '',
            orderTypeName: '',
            hospitalOrderCode: '',
            hospitalSalesReturnCode: '',
            startTime: '',
            endTime: ''
        },
        loading: false,
        orderId: '',
        visible: false
    };

    async componentDidMount() {
        await this.getData()
    }

    getData = async () => {
        this.setState({loading: true})
        const {salesReturnStatus, searchValue} = this.state
        let res = await apiGetReturnOrderDetails({
            salesReturnStatus,
            ...searchValue,
            ...this.state[`pageData${salesReturnStatus}`]
        })
        if (res.data && res.code === 0) {
            this.setState({
                [`pageData${salesReturnStatus}`]: {
                    pageNo: res.pageNo,
                    pageSize: res.pageSize
                },
                [`dataSource${salesReturnStatus}`]: res.data,
                [`total${salesReturnStatus}`]: res.totalCount,
                loading: false
            })
        } else {
            this.setState({loading: false})
        }
    }
    setTabKey = (salesReturnStatus) => {
        this.setState({salesReturnStatus}, () => {
            this.getData()
        })
    };
    pageChange = (pageNo, pageSize, index) => {
        this.setState({
            [`pageData${index}`]: {
                pageNo,
                pageSize,
            },
        }, () => this.getData());
    };
    dialogCancel = () => {
        this.setState({visible: false});
    };
    chargebackConfirm = (orderId) => {
        React.$confirm({
            title: "您确认同意此订单退款吗？",
            onOk: async () => {
                let res = await apiOrderRefundRefuse({
                    hospitalSalesReturnId: orderId,
                    salesReturnStatus: "9"
                })
                if (res.code === 0) {
                    React.$message({
                        type: 'info',
                        content: '退款成功'
                    })
                    this.getData()
                }
            },
        });
    };
    chargebackRefused = (orderId) => {
        this.setState({visible: true, orderId})
    };
    onFinish = async value => {
        this.setState({btnLoading: true})
        let res = await apiOrderRefundRefuse({
            ...value,
            hospitalSalesReturnId: this.state.orderId,
            salesReturnStatus: "4"
        })
        if (res.code === 0) {
            React.$message({
                type: 'info',
                content: '拒绝退款成功'
            })
            this.handleCancel()
            this.getData()
        }
        this.setState({btnLoading: false})
    }
    handleCancel = () => {
        this.setState({
            visible: false,
            orderId: ''
        })
    }
    setNickName = e => {
        this.setState({
            searchValue: {
                ...this.state.searchValue,
                nickName: e
            },
            pageData1: {
                pageNo: 1,
                pageSize: 10
            },
            pageData4: {
                pageNo: 1,
                pageSize: 10
            },
            pageData9: {
                pageNo: 1,
                pageSize: 10
            },
        }, () => {
            this.getData()
        })
    }
    setOrderCode = e => {
        this.setState({
            searchValue: {
                ...this.state.searchValue,
                hospitalOrderCode: e
            },
            pageData1: {
                pageNo: 1,
                pageSize: 10
            },
            pageData4: {
                pageNo: 1,
                pageSize: 10
            },
            pageData9: {
                pageNo: 1,
                pageSize: 10
            },
        }, () => {
            this.getData()
        })
    }
    setReturnCode = e => {
        this.setState({
            searchValue: {
                ...this.state.searchValue,
                hospitalSalesReturnCode: e
            },
            pageData1: {
                pageNo: 1,
                pageSize: 10
            },
            pageData4: {
                pageNo: 1,
                pageSize: 10
            },
            pageData9: {
                pageNo: 1,
                pageSize: 10
            },
        }, () => {
            this.getData()
        })
    }
    datePickerChange = e => {
        if (e) {
            this.setState({
                searchValue: {
                    ...this.state.searchValue,
                    startTime: getDateTime3(e[0]),
                    endTime: getDateTime3(e[1])
                },
                pageData1: {
                    pageNo: 1,
                    pageSize: 10
                },
                pageData4: {
                    pageNo: 1,
                    pageSize: 10
                },
                pageData9: {
                    pageNo: 1,
                    pageSize: 10
                },
            }, () => {
                this.getData()
            })
        } else {
            this.setState({
                searchValue: {
                    ...this.state.searchValue,
                    startTime: '',
                    endTime: ''
                },
                pageData1: {
                    pageNo: 1,
                    pageSize: 10
                },
                pageData4: {
                    pageNo: 1,
                    pageSize: 10
                },
                pageData9: {
                    pageNo: 1,
                    pageSize: 10
                },
            }, () => {
                this.getData()
            })
        }
    }

    render() {
        const operations = {
            right: (
                <Space>
                    <Search
                        onSearch={(e) => this.setNickName(e)}
                        style={{width: 150}}
                        placeholder={"用户昵称"}
                        allowClear
                        enterButton
                    />
                    <Search
                        onSearch={(e) => this.setOrderCode(e)}
                        style={{width: 180}}
                        placeholder={"请输入订单号"}
                        allowClear
                        enterButton
                    />
                    <Search
                        onSearch={(e) => this.setReturnCode(e)}
                        style={{width: 180}}
                        placeholder={"请输入退单号"}
                        allowClear
                        enterButton
                    />
                    <div>
                        <span>退单时间 </span>
                        <RangePicker onChange={(e) => this.datePickerChange(e)}/>
                    </div>
                </Space>
            ),
        };
        const {tabData, loading, visible, btnLoading} = this.state;
        return (
            <div className="p-layout-box">
                <Tabs
                    onChange={(value) => this.setTabKey(value)}
                    tabBarExtraContent={operations}
                >
                    {tabData.map((v, i) => {
                        return (
                            <TabPane tab={v.label} key={v.value}>
                                <div className="p-layout-content-pagination">
                                    <TheTable
                                        rowKey={record => record.orderId}
                                        scroll={{x: "max-content"}}
                                        columns={this.state[`columns${v.value}`]}
                                        dataSource={this.state[`dataSource${v.value}`]}
                                        loading={loading}
                                    />
                                    <ThePagination
                                        pageNo={this.state[`pageData${v.value}`].pageNo}
                                        pageSize={this.state[`pageData${v.value}`].pageSize}
                                        total={this.state[`total${v.value}`]}
                                        pageChange={(pageNo, pageSize) =>
                                            this.pageChange(pageNo, pageSize, v.value)
                                        }
                                    />
                                </div>
                            </TabPane>
                        );
                    })}
                </Tabs>
                <TheDialog
                    title="拒绝退款"
                    width={600}
                    visible={visible}
                    footer={null}
                    handleCancel={this.handleCancel}
                >
                    <Form onFinish={this.onFinish}>
                        <Form.Item name={'refuseReason'} label="拒绝原因" rules={[{required: true}]}>
                            <TextArea allowClear maxLength={50} showCount autoSize={{minRows: 6, maxRows: 6}}/>
                        </Form.Item>
                        <Form.Item name={'refuseComment'} label="拒绝备注" rules={[{required: true}]}>
                            <TextArea allowClear maxLength={50} showCount autoSize={{minRows: 6, maxRows: 6}}/>
                        </Form.Item>
                        <Form.Item>
                            <div style={{display: 'flex', justifyContent: 'flex-end', marginBottom: -30}}>
                                <Space>
                                    <Button onClick={this.handleCancel}>取消</Button>
                                    <Button loading={btnLoading} type="primary" htmlType="submit">确认</Button>
                                </Space>
                            </div>
                        </Form.Item>
                    </Form>
                </TheDialog>
            </div>
        );
    }
}

export default Chargeback;
